package com.qijian.common.timer;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public interface AbstractTimerTaskType {

    default TaskDefinition build(long id, Date deadline) {
        return build(id, new Date(), deadline);
    }

    default TaskDefinition build(long id, String type, Date deadline) {
        return build(id, type, new Date(), deadline);
    }

    default TaskDefinition build(long id, Date start, Date end) {
        if (start == null || end == null)
            return null;
        long between = DateUtil.between(start, end, DateUnit.SECOND, false);
        if (between < 0)
            return null;
        TaskDefinition task = new TaskDefinition();
        task.id = id;
        task.lead = lead();
        task.deadline = end;
        task.delay = Math.max(between - lead(), 0);
        task.delayUnit = TimeUnit.SECONDS;
        task.task = taskDo();
        return task;
    }

    default TaskDefinition build(long id, String type, Date start, Date end) {
        if (start == null || end == null)
            return null;
        long between = DateUtil.between(start, end, DateUnit.SECOND, false);
        if (between < 0)
            return null;
        TaskDefinition task = new TaskDefinition();
        task.id = id;
        task.type = type;
        task.lead = lead();
        task.deadline = end;
        task.delay = Math.max(between - lead(), 0);
        task.delayUnit = TimeUnit.SECONDS;
        task.taskWithType = taskDoWithType();
        return task;
    }

    default void addTimerTask(TaskDefinition definition) {
        TimerSchedule.addTask(definition);
    }

    default void stopTimerTask(Long id) {
        TimerSchedule.stopTask(id);
    }

    /**
     * @return 定义完的任务原型
     */
    List<TaskDefinition> generateTaskDefinition();

    /**
     * @return 要做的事
     */

    Consumer<Long> taskDo();

    Consumer<String> taskDoWithType();

    /**
     * @return 提前时间：秒
     */
    default int lead() {
        return 5 * 60;
    }

}
